//创建购物车模块
import {createSlice} from "@reduxjs/toolkit";

const cartSlice = createSlice({
    name:'cart',
    initialState:{
        cartList:localStorage.getItem('cartList')? JSON.parse(localStorage.getItem('cartList')):[]
    },
    reducers:{
        //加入购物车
        addCart(state,{type,payload}){
            const index = state.cartList.findIndex(v=>v.id===payload.id)
            if(index>-1){
                state.cartList[index].buyNum+=1
            }else{
                state.cartList.unshift({...payload,buyNum:1})
            }
            localStorage.setItem('cartList',JSON.stringify(state.cartList))
        },
    //    操作购物车数量
        changeNum(state,{type,payload}){
            const index = state.cartList.findIndex(v=>v.id===payload.id)
            state.cartList[index].buyNum += payload.num
            if(state.cartList[index].buyNum<=0){
                state.cartList.splice(index,1)
            }
            localStorage.setItem('cartList',JSON.stringify(state.cartList))
        }
    }
})
export const {addCart,changeNum} = cartSlice.actions
export default cartSlice